<?php

namespace Seller\Controller;

class OrderController extends BaseController {

    /**
     * 分销订单列表
     */
    public function distributionList() {
        $res = I('get.');
        if ($res) {
            foreach ($res as $k => $v) {
                $this->assign($k, $v);
            }
        }
        $status = in_array($this->__get['status'], array('1', '2', '3')) ? ( $this->__get['status'] - 1) : '1';
        $where['o.status'] = $status;
        $where['o.distribution_customer_id'] = $this->__seller_info['id'];
        $data = D('order')->getList($where);
        $this->assign('data', $data);
        $this->assign('customer_id', $this->__seller_info['id']);
        //全部有效订单
        $where['o.status'] = 1;
        $this->assign('order_total', M('order')->alias('o')->where($where)->count());
        //草稿订单
        $where['o.status'] = 0;
        $this->assign('draft_order_total', M('order')->alias('o')->where($where)->count());
        //失效订单
        $where['o.status'] = 2;
        $this->assign('invalid_order_total', M('order')->alias('o')->where($where)->count());
        $this->assign('status', $status);
        $this->display();
    }

    /**
     * 供应订单列表
     */
    public function supplyList() {
        $string = ( $this->__get['status'] == 2 ? 'ol.`status` = 1' : 'ol.`status` = 2' ) . ' AND ol.`pay_status` > 0';
        $list = M('order_line')->alias('ol')->join('__ORDER__ o ON o.id = ol.order_id')->where(array('ol.supply_customer_id' => $this->__seller_info['id'] ,'_string' => $string))
                        ->join('__CUSTOMER__ c ON c.id = o.distribution_customer_id')
                        ->field('c.shop_name,o.buyer_name,ol.ref,ol.num,ol.supply_price,o.create_time,o.trade_pattern,ol.pay_status,ol.express_name,o.id,ol.supply_customer_id')
                        ->page($this->__page, $this->__row)->order('o.id DESC')->group('ol.order_id')->select();
        $total = M('order_line')->alias('ol')->join('__ORDER__ o ON o.id = ol.order_id')->where(array('ol.supply_customer_id' => $this->__seller_info['id'] , '_string' => $string))
                        ->join('__CUSTOMER__ c ON c.id = o.distribution_customer_id')->field('COUNT(DISTINCT o.id) AS total')->find();
        if ($lists) {
            foreach ($list as $k => $v) {
                $amount_total = 0;
                //获得总金额
                $order_line_list = M('order_line')->where(array('order_id' => $v['id']))->field('num,supply_price')->select();
                foreach ($order_line_list as $ke => $va) {
                    $amount_total += $va['num'] * $va['supply_price'];
                }
                $list[$k]['amount_total'] = $amount_total;
            }
        }
        $this->__assignPage($total['total']);
        $this->assign('lists', $list);
        //获得已发货总数
        $this->assign('yes_total', M('order_line')->where(array("`supply_customer_id` = {$this->__seller_info['id']} AND `status` >= 2" ))->getField('COUNT( DISTINCT order_id )'));
        //获得未发货总数
        $this->assign('no_total', M('order_line')->where(array("`supply_customer_id` = {$this->__seller_info['id']} AND `status` = 1"))->getField('COUNT( DISTINCT order_id )'));
        $this->display();
    }
    
     /*     * *
     * 
     * 供应订单详情
     */

    function supplyDetail() {
        if( !isset($this->__get['ref']) || !preg_match('/^[0-9]+$/is' , $this->__get['ref']) ) $this->error( '订单号错误' );
        //查询订单信息
        $order_line = M('order_line')->where(array('supply_customer_id' => $this->__seller_info['id'] , 'ref' => $this->__get['ref']))->select();
        //订单信息验证
        if( !$order_line ) $this->error( '订单不存在' );
        $order_info = array();
        //组合总金额
        foreach( $order_line as $key => $value ) {
            $order_info['sub_total'] += $value['supply_price'] * $value['num'] + $value['fee'];
            $order_info['ref'] = $value['ref'];
            $order_info['pay_status'] = $value['pay_status'];
            $order_info['express_name'] = $value['express_name'];
            $order_info['payment_info']['payment_no'] = $value['payment_no'];
            $order_info['payment_info']['pay_type'] = $value['pay_type'];
            $order_info['payment_info']['pay_money'] = $value['pay_money'];
            $order_info['payment_info']['pay_time'] = $value['pay_time'];
            $order_info['payment_info']['pay_status'] = $value['pay_status'];
            //获得已支付的金额
            $order_line[$key]['surely_total'] = M('order_line_pay')->where(array('order_line_id' => $value['id'],'pay_status' => 1))->sum('price');
        }
        $order_info['order_line'] = $order_line;
        //获得大订单信息
        $order = M('order')->alias('o')->join('__CUSTOMER__ c ON c.id = o.distribution_customer_id')->where(array('o.ref' => $order_info['ref']))->field('o.*,c.shop_name')->find();
        if( !$order ) $this->error( '订单不存在' );
        $order_info['shop_name'] = $order['shop_name'];
        $order_info['date_order'] = $order['date_order'];
        $order_info['id'] = $order['id'];
        $order_info['discount'] = $order['discount'];
        $order_info['delivery_fee'] = $order['delivery_fee'];
        $order_info['receive_info'] = $order['receive_info'];
        $order_info['create_time'] = $order['create_time'];
        $order_info['distribution_customer_id'] = $order['distribution_customer_id'];
        
        //获得来源平台
        $this->assign('platform_name', M('customer_platform_bind')->where(array('id' => $order_info['platform_id']))->getField('name'));
        $send_types = explode('|', C('SEND_TYPES'));
        $this->assign('send_types', $send_types);
        $this->assign("val", $order_info);
        $this->assign('type', I('get.type'));
        $this->display();
    }

    /*     * *
     * 
     * 分销订单详情
     */

    function detail() {
        $ref = I("get.ref", "0");
        if (!$ref) {
            $this->error("参数错误", U("index"));
        }
        $m = D("order");
        $res = $m->relation(true)->where(array('ref' => $ref,'distribution_customer_id' => $this->__seller_info['id']))->find();
        if( !$res ) $this->error( '订单不存在' );
        $send_express = 0;
        if ($res && isset($res['order_line'])) {
            $res['orderAmount'] = 0;
            foreach ($res['order_line'] as $key => $value) {
                if (!$value['express_name']) {
                    $send_express = 1;
                }
                $res['order_line'][$key]['earn13'] = M('goods')->where(array('sku' => $value['sku']))->getField('earn13');
                $res['orderAmount']+= $res['order_line'][$key]['supply_price'] * $res['order_line'][$key]['num'];
            }
        }
        //分供应商组合数据
        foreach( $res['order_line'] as $key => $value ) {
            $res['order_customer_line'][$value['supply_customer_id']]['list'][] = $value;
            $res['order_customer_line'][$value['supply_customer_id']]['supply_name'] = M('customer')->where(array('id' => $value['supply_customer_id']))->getField('shop_name');
            $res['order_customer_line'][$value['supply_customer_id']]['price_total'] += $value['supply_price'] * $value['num'] + $value['fee'];
            $res['order_customer_line'][$value['supply_customer_id']]['goods_total'] += 1;
            $res['order_customer_line'][$value['supply_customer_id']]['pay_status'] = $value['pay_status'];
            $res['order_customer_line'][$value['supply_customer_id']]['status'] = $value['status'];
            $surely_total  = order_status_surely_pay_price( $value['id'] );
            $res['order_customer_line'][$value['supply_customer_id']]['surely_total'] += $surely_total[0];
            $res['order_customer_line'][$value['supply_customer_id']]['express_name'] = $value['express_name'];
            $res['order_customer_line'][$value['supply_customer_id']]['express_no'] = $value['express_no'];
            $res['order_customer_line'][$value['supply_customer_id']]['send_time'] = $value['send_time'];
            $res['order_customer_line'][$value['supply_customer_id']]['payment_no'] = $value['payment_no'];
            $res['order_customer_line'][$value['supply_customer_id']]['pay_type'] = $value['pay_type'];
            $res['order_customer_line'][$value['supply_customer_id']]['pay_money'] = $value['pay_money'];
            $res['order_customer_line'][$value['supply_customer_id']]['pay_time'] = $value['pay_time'];
            $res['order_customer_line'][$value['supply_customer_id']]['ref'] = $value['ref'];

            if ($res['express_send_type'] == 1){
                $res['order_customer_line'][$value['supply_customer_id']]['fee'] = M('logistics_needs')->where(array('ref' => $value['ref']))->sum('price');
            }elseif($res['express_send_type'] == 0){
                $res['order_customer_line'][$value['supply_customer_id']]['fee'] += $value['fee'];
            }else{
                $res['order_customer_line'][$value['supply_customer_id']]['fee'] = 0;
            }
            $res['delivery_fee'] = $res['order_customer_line'][$value['supply_customer_id']]['fee'];
        }
        unset( $res['order_line'] );
        $send_types = explode('|', C('SEND_TYPES'));

        if ($res['express_send_type'] ==1){
            $needid = M('logistics_needs')->field('id,ref,is_choice,express_order_id')->where(array('ref' => $res['ref']))->find();
            if ($needid){
                $supply_id = M('logistics_order')->field('supply_id')->find($needid['express_order_id']);
                if ($supply_id){
                    $company_name = M('logistics_supply')->field('company_name')->find($supply_id['supply_id']);
                }
            }
        }else{
            $needid = 0;
        }
        $this->assign("needid", $needid);
        $this->assign("company_name", $company_name['company_name']);

        //获得来源平台
        $this->assign('platform_name', M('customer_platform_bind')->where(array('id' => $res['platform_id']))->getField('name'));
        $this->assign('send_types', $send_types);
        $this->assign("val", $res);
        $this->assign('type', I('get.type'));
        $this->assign('send_express', $send_express);
        $this->display();
    }

    //获取支付信息
    public function pay() {
        if (!preg_match('/^[0-9]+\_[0-9]+$/is', $this->__get['ref'])) {
            tipsDivError('订单号错误');
        }
        $ref = explode('_', $this->__get['ref']);
        $order_line_model = M('order_line');
        //获得支付订单状态
        $order_info = $order_line_model->alias('ol')->join('__ORDER__ o ON o.id = ol.order_id')
                                       ->where(array('o.distribution_customer_id' => $this->__seller_info['id'],'ol.ref' => $ref[0], 'ol.supply_customer_id' => $ref[1]))->field('ol.*')->select();
        //判断订单是否存在
        if (!$order_info)
            tipsDivError('支付订单信息不存在');
        //判断订单是否已经支付
        $status_flat = true;
        foreach( $order_info as $key => $val ) {
            $val['pay_status'] == 1 || $val['pay_status'] == 0 ? $status_flat = false : '';
        }
        if ( $status_flat === true )
            tipsDivError('订单已支付请勿重复支付');
        //获得本次应该支付的金额
        $surely_price = 0;
        foreach( $order_info as $key => $value ) {
            $surely_total  = order_status_surely_pay_price( $value['id'] );
            $surely_price += $surely_total[0];
        }
        
        $payInfo = M('customer')->where(array('id' => $order_info['supply_customer_id']))->field('weixin_pay_id,alipay_pay_id')->find();
        //如果没有配置支付 默认平台支付
        if (!$payInfo['weixin_pay_id']) {
            $payInfo['weixin_pay_id'] = M('payment_config')->where(array('type' => 2, 'default' => 1, 'status' => 1))->getField('id');
        }
        if (!$payInfo['alipay_pay_id']) {
            $payInfo['alipay_pay_id'] = M('payment_config')->where(array('type' => 1, 'default' => 1, 'status' => 1))->getField('id');
        }
        $this->assign("val", array('pay_total' => $surely_price , 'id' => $order_info[0]['id']));
        $this->assign("supplyInfo", $supplyInfo);
        $this->assign('payInfo', $payInfo);
        $this->assign('local_price' , M('customer')->where(array('id' => $this->__seller_info['id']))->getField('money'));
        $this->display();
    }
    
    public function delivery() {
        if (!isset($this->__get['ref']) || !preg_match('/^[0-9]+$/is', $this->__get['ref']))
            $this->error('发货数据错误');
        $order_line_model = M('order_line');
        //获得支付订单状态
        $order_info = $order_line_model->alias('ol')->join('__ORDER__ o ON o.id = ol.order_id')
                        ->where(array('ol.supply_customer_id' => $this->__seller_info['id'], 'ol.ref' => $this->__get['ref']))->field('ol.*,o.receive_info')->find();
        //判断订单是否存在
        if (!$order_info)
            $this->error('支付订单信息不存在');
        //判断订单是否已经发货
        if ($order_info['express_name'])
            $this->error('已发货无需重新发货');
        $send_types = explode('|', C('SEND_TYPES'));
        $this->assign('send_types', $send_types);
        $this->assign('ref', $order_info);
        $this->display();
    }

    //发货
    public function send() {
        $data = I('post.');
        if( !$data ) exit;
        $order_line_model = M("order_line");
        $msg ['errno'] = 0;
        $msg ['error'] = "发货失败";
        $data['send_time'] = time();
        $res = $order_line_model->where(array('ref' => $data['ref'] , 'supply_customer_id' => $this->__seller_info['id'], '_string' => 'express_name = ""'))->find();
        if( !$res ) {
            $msg ['error'] = "订单已发货，无需重新发货";
            $this->ajaxReturn($msg);
            exit();
        }
        if (M('order_line')->where(array('ref' => $data['ref'] , 'supply_customer_id' => $this->__seller_info['id']))->save($data)) {
            M('system_message')->add(array('role' => 1, 'target_id' => M('order')->where(array('ref' => $data['ref']))->getField('distribution_customer_id'), 'title' => '发货消息', 'content' => '你的订单' . $data['ref'] . '供应商【'.$this->__seller_info['shop_name'].'】已发货', 'create_time' => date('Y-m-d H:i', time())));
            $orderLine = M('order_line')->where(array('ref' => $data['ref'] , 'supply_customer_id' => $this->__seller_info['id']))->select();
            foreach ($orderLine as $key => $val) {
                M('goods_supply')->where(array('id' => $val['supply_product_id']))->setDec('lock_stock_num', $val['num']); //解锁库存
                M('goods_supply')->where(array('id' => $val['supply_product_id']))->setInc('sale_stock_num', $val['num']); //解锁库存
            }
            $msg ['errno'] = 1;
            $msg ['error'] = "发货成功";
            
            //更改小订单发货订单状态
            $order_line_model->where(array('ref' => $data['ref']))->save(array('status' => 2));
            //更改大订单发货状态
            $send_total_num = $order_line_model->where(array('ref' => $data['ref'],'_string' => '`status` = 2'))->count();
            if( $send_total_num > 0 && $send_total_num == $order_line_model->where(array('ref' => $data['ref']))->count() ) {
                M('order')->where(array('ref' => $data['ref']))->save(array('express_send_status' => 2));
            } else {
                M('order')->where(array('ref' => $data['ref']))->save(array('express_send_status' => 1));
            }
        }
        $this->ajaxReturn($msg);
    }

    /**
     * 取消订单
     */
    public function cancel() {
        if (!preg_match('/^[0-9]+((\,[0-9]+)+)?$/is', $this->__get['id'])) {
            $this->error('数据格式错误！');
        }
        if (M('order')->where(array('id' => array('in', $this->__get['id']), 'distribution_customer_id' => $this->__seller_info['id']))->save(array('status' => 2))) {
            $this->success('订单取消成功！');
        } else {
            $this->error('订单取消失败！');
        }
    }

    /**
     * 确认订单
     */
    public function confirm() {
        if (!preg_match('/^[0-9]+((\,[0-9]+)+)?$/is', $this->__get['id'])) {
            $this->error('数据格式错误！');
        }
        if (M('order')->where(array('id' => array('in', $this->__get['id']), 'distribution_customer_id' => $this->__seller_info['id']))->save(array('status' => 1))) {
            $this->success('订单确认成功！');
        } else {
            $this->error('订单确认失败！');
        }
    }

    /**
     * 订单删除
     */
    public function delete() {
        if (!preg_match('/^[0-9]+((\,[0-9]+)+)?$/is', $this->__get['id'])) {
            $this->error('数据格式错误！');
        }
        if (M('order')->where(array('id' => array('in', $this->__get['id']), 'distribution_customer_id' => $this->__seller_info['id']))->delete()) {
            //删除订单产品信息
            M('order_line')->where(array('order_id' => array('in', $this->__get['id'])))->delete();
            //删除推送信息
            M('order_pay_send')->where(array('order_id' => array('in', $this->__get['id'])))->delete();
            //删除支付信息
            M('order_payment')->where(array('order_id' => array('in', $this->__get['id'])))->delete();
            $this->success('订单删除成功！');
        } else {
            $this->error('订单删除失败！');
        }
    }

    /**
     * 提醒供货商发货
     */
    public function remind() {
        if (!preg_match('/^[0-9]+$/is', $this->__get['id'])) {
            $this->error('数据格式错误！');
        }
        $order_info = M('order')->where(array('id' => $this->__get['id'], 'distribution_customer_id' => $this->__seller_info['id']))->find();
        if (!$order_info)
            $this->error('信息不存在');
        if (date('Y-m-d', $order_info['remind_time']) == date('Y-m-d'))
            $this->error('非常抱歉，每天只能提醒一次！');
        $order_line = M('order_line')->where("`order_id` = {$this->__get['id']} AND `express_name` = ''")->field('supply_customer_id')->select();
        if ($order_line) {
            foreach ($order_line as $key => $value) {
                M('system_prompt')->add(array(
                    'customer_id' => $value['supply_customer_id'],
                    'type' => 2,
                    'target_id' => $order_info['id'],
                    'title' => '分销商【' . $this->__seller_info['shop_name'] . '】提醒您订单【' . $order_info['ref'] . '】该发货了！',
                    'create_time' => time()
                ));
            }
        }
        //更新提醒时间
        M('order')->where(array('id' => $order_info['id']))->save(array('remind_time' => time()));
        $this->success('提醒成功');
    }
    
    /**
     * 用户确认收货
     */
    public function goodsReceipt() {
        if( !isset( $this->__get['id'] ) || !preg_match('/^[0-9]+\_[0-9]+$/is', $this->__get['id'] )) $this->error( '信息错误' );
        $data = explode( '_' , $this->__get['id'] );
        $order_line = M('order_line')->where(array('ref' => $data['0'] , 'supply_customer_id' => $data[1]))->find();
        if( !$order_line || !in_array( $order_line['status'], array(2,3)) ) $this->error( '信息不存在或状态不正确' );
        if( $order_line['status'] == 4 ) {
            $this->error( '已收货，无需在确认收货' );
        }
        M('order_line')->where(array('ref' => $data['0'] , 'supply_customer_id' => $data[1]))->save( array( 'status' => 4) );
        //通知供应商已完成
        insertSystemInfo( $order_line['supply_customer_id'] , '订单【'.$order_line['ref'].'】已收货' , "尊敬的【".M('customer')->where(array('id' => $order_line['supply_customer_id']))->getField('shop_name')."】您好，您发货的订单【{$order_line['ref']}】用户【{$this->__seller_info['shop_name']}】已收货。");
        //获得供应商的订单总金额
        $supply_price_total = supplyOrderTotal( $order_line['ref'] , $order_line['supply_customer_id']); 
        //经验升级
        upgradeCheck( $this->__seller_info['id'] , ceil($supply_price_total) );
        
        //供应产品信息统计
        $order_list = M('order_line')->where(array('ref' => $data['0'] , 'supply_customer_id' => $data[1]))->select();
        //判断是否锁货
        foreach( $order_list as $key => $order_line ) {
            if( $order_line['source_type'] == 1 ) {
                goods_supply_count_save( $order_line['supply_product_id'] , 'total_sale' , $order_line['num']);
                goods_supply_count_save( $order_line['supply_product_id'] , 'residue_total_stock,residue_lock_stock' , $order_line['num'] , 2);
                goods_supply_count_save( $order_line['supply_product_id'] , 'lock_order_num' , 1);
                goods_supply_count_save( $order_line['supply_product_id'] , 'lock_order_price,total_sale_price' , $order_line['sub_total']);
            } else {
                goods_supply_count_save( $order_line['supply_product_id'] , 'total_sale' , $order_line['num']);
                goods_supply_count_save( $order_line['supply_product_id'] , 'use_total_stock,residue_total_stock' , $order_line['num'] , 2);
                //判断是批发还是零售
                if( M('goods_supply')->where(array('id' => $order_line['supply_product_id']))->getField('wholesale_start_num') < $order_line['num'] ) {
                    goods_supply_count_save( $order_line['supply_product_id'] , 'acting_order_num' ,1);
                    $fields = 'acting_order_price';
                } else {
                    goods_supply_count_save( $order_line['supply_product_id'] , 'wholesale_order_num' , 1);
                    $fields = 'wholesale_order_price';
                }
                goods_supply_count_save( $order_line['supply_product_id'] , 'total_sale_price,'.$fields , $order_line['sub_total']);
            }
        }
        $this->success('收货成功');
    }

}
